import JSEncrypt from 'jsencrypt';
import {getRsaPublicKey} from "@/api/system";

/**
 * 使用RSA公钥加密数据
 * @param data 待加密的数据
 * @param key 公钥
 * @returns 加密后的字符串
 */
export function rsaEncrypt(data: string, key: string): string {
  try {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(key);
    return encrypt.encrypt(data) as string;
  } catch (error) {
    throw new Error('RSA加密失败: ' + error);
  }
}


export async function projectRsaEncrypt(data: string): Promise<string> {
  const response = await getRsaPublicKey()
  try {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(response.data);
    return Promise.resolve(encrypt.encrypt(data) as string);
  } catch (error) {
    console.error('RSA加密失败: ' + error)
    return Promise.reject(error);
  }
}
